import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotInteractableException, ElementClickInterceptedException, WebDriverException
from time import sleep, time
import sys
import csv

mainAccounts = list()
subAccounts = list()
startTime = list()
giftName = ""
giftNum = 0

br1 = None
br2 = None
wait1 = None
wait2 = None
littleName = ''
mUn = ""
mPw = ""
sUn = ""
sPw = ""


def getAccount():
    global mainAccounts, subAccounts, giftName, giftNum
    with open('main.csv') as f:
        r = csv.reader(f)
        mainAccounts = list(r)

    with open('sub.csv') as f:
        r = csv.reader(f)
        subAccounts = list(r)

    for i in range(len(mainAccounts)):
        startTime.append(0)

    f = open("gift.txt")
    gift = f.read().split(",")
    giftName = gift[0]
    giftNum = int(gift[1])


timeout = 40


def initBrowser(which):
    global br1, br2, wait1, wait2
    profile = FirefoxProfile()
    profile.set_preference('network.proxy.type', 1)
    profile.set_preference('network.proxy.socks', '127.0.0.1')
    profile.set_preference('network.proxy.socks_port', 1080)
    profile.set_preference('network.proxy.ssl', '127.0.0.1')
    profile.set_preference('network.proxy.ssl_port', 1080)
    profile.set_preference('network.proxy.http', '127.0.0.1')
    profile.set_preference('network.proxy.http_port', 1080)
    if which == 1:
        br1 = webdriver.Firefox()
        br1.set_page_load_timeout(timeout)
        br1.set_script_timeout(timeout)
        wait1 = WebDriverWait(br1, timeout)
    elif which == 2:
        br2 = webdriver.Firefox()
        wait2 = WebDriverWait(br2, timeout)
        br2.set_page_load_timeout(timeout)
        br2.set_script_timeout(timeout)


def reOpenBr(which):
    if which == 1 and br1 != None:
        br1.quit()
    elif which == 2 and br2 != None:
        br2.quit()
    initBrowser(which)


def getVerifyCode(username, password):
    br = webdriver.Firefox()
    br.set_page_load_timeout(timeout)
    br.set_script_timeout(timeout)
    wait = WebDriverWait(br, timeout)
    try:
        br.get("http://mail.9fa.info:8080")
    except TimeoutException:
        pass

    wait.until(EC.presence_of_element_located(
        (By.ID, "rcmloginuser"))).send_keys(username)
    wait.until(EC.presence_of_element_located(
        (By.ID, "rcmloginpwd"))).send_keys(password)
    try:
        br.find_element_by_id("rcmloginsubmit").click()
    except TimeoutException:
        pass

    table = wait.until(EC.presence_of_element_located((By.ID, "messagelist")))
    table.find_elements_by_class_name("message")[0].click()


def login1(br, wait, un, pw):
    try:
        br.get("https://store.steampowered.com/login")
    except TimeoutException:
        # print("timeout")
        pass

    if br.current_url == "https://store.steampowered.com/":
        print("login already")
        return

    wait.until(EC.presence_of_element_located(
        (By.ID, 'input_username'))).send_keys(un)

    br.find_element_by_id('input_password').send_keys(pw)
    br.find_element_by_css_selector(
        '[class="btnv6_blue_hoverfade  btn_medium"]').click()

    try:
        authcode = wait.until(
            EC.visibility_of_element_located((By.ID, "authcode")))
    except TimeoutException:
        return

    if sys.version > '3':
        a = input("continue:")
    else:
        a = raw_input("continue:")
    authcode.send_keys(a)
    authcode.send_keys(Keys.ENTER)
    try:
        wait.until(EC.element_to_be_clickable(
            (By.ID, "success_continue_btn"))).click()
    except TimeoutException:
        # print("timeout")
        pass


def login2(br, wait, un, pw):
    try:
        br.get("https://steamcommunity.com/login/")
    except TimeoutException:
        # print("timeout")
        pass

    wait.until(EC.presence_of_element_located(
        (By.ID, 'steamAccountName'))).send_keys(un)
    br.find_element_by_id(
        'steamPassword').send_keys(pw)
    br.find_element_by_id('SteamLogin').click()

    try:
        authcode = wait.until(
            EC.visibility_of_element_located((By.ID, "authcode")))
    except TimeoutException:
        return

    if sys.version > '3':
        a = input("continue:")
    else:
        a = raw_input("continue:")
    authcode.send_keys(a)
    authcode.send_keys(Keys.ENTER)

    try:
        wait.until(EC.element_to_be_clickable(
            (By.ID, "success_continue_btn"))).click()
    except TimeoutException:
        # print("timeout")
        pass


def rename():
    a = wait1.until(EC.presence_of_element_located(
        (By.CLASS_NAME, "user_avatar")))
    try:
        br1.get(a.get_attribute("href") + "edit")
    except TimeoutException:
        # print("timeout")
        pass

    e = wait1.until(EC.presence_of_element_located(
        (By.NAME, 'real_name')))
    e.clear()
    e.send_keys("1")

    try:
        br1.find_element_by_class_name("forum_manage_actions").find_element_by_css_selector(
            '[class="btn_green_white_innerfade btn_medium"]').click()
        # wait1.until(EC.element_to_be_clickable(
        #     (By.CSS_SELECTOR, '[class="btn_green_white_innerfade btn_medium"]'))).click()
    except TimeoutException:
        # print("timeout")
        pass

    try:
        wait1.until(EC.element_to_be_clickable(
            (By.CSS_SELECTOR, '[class="btn_grey_white_innerfade btn_small"]'))).click()
    except TimeoutException:
        # print("timeout")
        pass


def invite():
    global littleName
    try:
        br2.get(br1.current_url)
    except TimeoutException:
        # print("timeout")
        pass

    try:
        div = wait2.until(EC.presence_of_element_located(
            (By.CLASS_NAME, "profile_header_centered_persona")))
        littleName = div.find_element_by_class_name("actual_persona_name").text
        print(littleName)
        wait2.until(EC.element_to_be_clickable(
            (By.ID, 'btn_add_friend'))).click()
        return True
    except TimeoutException:
        print("oh no!")
        # print("timeout")
        return False


def acceptInvite():
    try:
        if br1.current_url.endswith("/"):
            br1.get(br1.current_url + 'home/invites')
        else:
            br1.get(br1.current_url + '/home/invites')
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        br1.find_elements_by_class_name(
            "btnv6_white_transparent")[0].click()
    except IndexError:
        pass


def buyGift():
    wait2.until(EC.presence_of_element_located(
        (By.ID, "store_nav_search_term"))).send_keys(giftName)
    try:
        br2.find_element_by_id(
            "store_nav_search_term").send_keys(Keys.ENTER)
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.presence_of_all_elements_located(
            (By.CLASS_NAME, 'search_result_row')))[giftNum].click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.element_to_be_clickable(
            (By.CLASS_NAME, 'btnv6_green_white_innerfade'))).click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.element_to_be_clickable(
            (By.ID, 'btn_purchase_gift'))).click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        br2.find_element_by_id('input_password').send_keys(mPw)
        br2.find_element_by_css_selector(
            '[class="btnv6_blue_hoverfade  btn_medium"]').click()
    except NoSuchElementException:
        try:
            br2.find_element_by_id(
                'steamPassword').send_keys(mPw)
            br2.find_element_by_id('SteamLogin').click()
        except (NoSuchElementException, TimeoutException):
            pass
    except TimeoutException:
        pass

    friends = wait2.until(EC.presence_of_element_located(
        (By.ID, "friends_chooser")))
    name = friends.find_elements_by_class_name("friend_name")
    for i in range(len(name)):
        if name[i].text == littleName:
            try:
                friends.find_elements_by_class_name(
                    "friend_block")[i].click()
                br2.find_elements_by_class_name(
                    "btnv6_green_white_innerfade")[0].click()
            except TimeoutException:
                # print("timeout")
                pass
            break
    try:
        wait2.until(EC.presence_of_element_located(
            (By.ID, "gift_recipient_name"))).send_keys("1")
        br2.find_element_by_id("gift_message_text").send_keys("1")
        br2.find_element_by_id("gift_signature").send_keys("1")
    except ElementNotInteractableException:
        return 1

    try:
        br2.find_element_by_id("submit_gift_note_btn").click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.element_to_be_clickable((By.ID, "accept_ssa"))).click()
    except TimeoutException:
        return 2
    try:
        br2.find_element_by_id("purchase_button_bottom").click()
    except TimeoutException:
        #        print("timeout")
        pass
    return 0


def acceptGift():
    try:
        br1.get("https://store.steampowered.com/gifts/")
    except TimeoutException:
     #        print("timeout")
        pass

    btns = wait1.until(EC.presence_of_all_elements_located(
        (By.CLASS_NAME, "btn_green_white_innerfade")))
    for btn in btns:
        try:
            btn.click()
        except ElementClickInterceptedException:
            return

        sleep(2)

        ll = br1.find_elements_by_class_name("newmodal_buttons")
        for l in ll:
            try:
                l.find_element_by_class_name(
                    "btn_grey_white_innerfade").click()
            except ElementClickInterceptedException:
                pass


if __name__ == '__main__':
    getAccount()
    i = 0
    j = 0
    lastJ = 0
    br2ReOpen = True
    exception = False
    while len(mainAccounts) > 0 and j < len(subAccounts):
        # main == i2, sub == j1
        if j - lastJ == 10:
            lastJ = j
            i += 1
            br2ReOpen = True
        if i >= len(mainAccounts):
            i = 0
        if br2ReOpen:
            reOpenBr(2)
            if not exception:
                while time() - startTime[i] < 3700:
                    print("Please wait, %d seconds left" %
                          (3700 - (int)(time() - startTime[i])))
                    sleep(100)
                startTime[i] = time()
        exception = False

        reOpenBr(1)
        print("process:%s - %s\t%d - %d\t%d - %d" %
              (mUn, sUn, i, j, len(mainAccounts), len(subAccounts)))
        mUn = mainAccounts[i][2].strip()
        mPw = mainAccounts[i][3].strip()
        sUn = subAccounts[j][2].strip()
        sPw = subAccounts[j][3].strip()
        littleName = sUn

        try:
            login1(br1, wait1, sUn, sPw)
            rename()

            if br2ReOpen:
                login2(br2, wait2, mUn, mPw)

            if invite():
                sleep(5)
                acceptInvite()

            if br2ReOpen:
                login1(br2, wait2, mUn, mPw)
                br2ReOpen = False
            else:
                try:
                    br2.get("https://store.steampowered.com/")
                except TimeoutException:
                    pass

            buyResult = buyGift()
            if buyResult == 1:
                print(sUn + " already had this gift!")
                j += 1
                continue
            elif buyResult == 2:
                print(mUn + " has no money!")
                del mainAccounts[i]
                del startTime[i]
                br2ReOpen = True
                continue
            elif buyResult == 0:
                pass

            sleep(5)
            #acceptGift()
        except (NoSuchElementException, TimeoutException, WebDriverException) as e:
            print(e)
            br2ReOpen = True
            exception = True
            continue
        j += 1
    print('Over!')
